import React, { useState, useEffect } from 'react';
import { cline, obj_str, useCmd, uDb, is_empty, obj_empty, loc } from 'sui';
import { Bind } from 'manage/station/ctl';

const ToolStep = ({ cur, hreturn }) => {
    const [main_user, mainUser] = useState([]);
    const [checked, setChecked] = useState([]);
    const umd = useCmd("bom/listsn", null, { k: obj_str(cur, "sn") });

    useEffect(() => {
        uDb(null, "file/list/step", {line: cline()}, r => mainUser(r), e => mainUser(null));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const remove = (v) => {
        const cmd = {
            line: cline(),
            k: obj_str(cur, "sn"),
            sn: v,
        };

        umd.update("bom/rm", cmd, () => setChecked([]));
    };

    const addUser = () => {
        if (obj_empty(cur) || is_empty(checked)) {
            return;
        }

        const val = {};

        checked.forEach(d => {
            val[d] = [];
        });

        const cmd = {
            line: cline(),
            k: obj_str(cur, "sn"),
            v: val
        };
        umd.update("bom/add", cmd, () => setChecked([]));
    };

    return <Bind umd={umd} cur={cur} hreturn={hreturn} hadd={addUser} checked={checked} setChecked={setChecked} title={loc("l_149")}
                 hremove={remove} main={main_user} setMain={mainUser}/>;
};

export {ToolStep};
